import React, {useEffect, useState} from 'react';
import CommentListItem from "@/components/Comment/List/item";
import {View, Button, Image} from "@tarojs/components";
import Taro from "@tarojs/taro";
import {getCommentCountServer, getCommentSelectionServer} from "@/services/comment";
import picEmpty from "@/components/Comment/List/empty.jpg";

import './index.scss'



//精选评价
//type 1 商城 2本地生活
//limit 最大显示数量,0不限
const CommentChoice = React.forwardRef(({type=0,topicId=0,appId="thjs_takeout_org",showRate=false,reload=0,children,limit=2,onLoad=()=>{}})=>{
  const [state, updateState] = useState({
    finished:false,
    data:[]
  });

  const [count,setCount] = useState(0)

  const setState=(data)=>{
    updateState({...state,...data})
  }

  //加载数据
  const load=async ()=>{
    const params={
      type,
      topicId,
      appId
    }
    getCommentCountServer({ topicId,appId }).then((res) => {
      const num=res.content.find((item) => item.id == 0).count
      setCount(num)
      onLoad(num)
    });
    getCommentSelectionServer(params).then(res=>{
      if(res.code==1&&res.content.length){
        setState({
          finished:true,
          data:res.content
        })
      }else{
        setState({
          finished:true
        })
      }
    })
  }

  //初始化
  useEffect(()=>{
    topicId&&type&&load()
  },[topicId,type,reload])

  const handleClick=()=>{
    Taro.navigateTo({
      url:`/orderSubPack/commentAll/index?id=${topicId}&appId=${appId}`
    });
  }

  if(!count&&state.finished){
    return children||(
      <View className="commentEmpty">
        <Image src={picEmpty} className="pic" />
        <View className="msg">暂无评价</View>
      </View>
    )
  }else{
    return (
      <View className="commentListBox">
        {(limit?state.data.slice(0,limit):state.data).map((item,idx)=>(
          <CommentListItem key={idx} data={item} showRate={showRate} />
        ))}
        {!!limit&&(count>=limit)&&(
          <Button className="commentMoreBtn" onClick={handleClick}>
            查看全部评价
          </Button>
        )}
      </View>
    )
  }
})

export default CommentChoice
